//小仓库
import { defineStore } from "pinia";
import { ref, reactive } from "vue";
import { reqLogin, reqUserInfo, reqLogout } from "../../api/user";
import type { loginForm, loginResponseData,userInfoData } from "../../api/user/type";
import routes from "../../router/routes";
import type { RouteRecordRaw } from "vue-router";
const useUserStore = defineStore(
  "User",
  () => {
    //引入常量路由
    const menuRoutes:RouteRecordRaw[] = routes
    const token = ref<string>();
    const userList = reactive({
      username:'',
      avatar:''
    })
    const useLogin = async (data: loginForm) => {
      const res:loginResponseData = await reqLogin(data);
      // console.log(res);
      if(res.code === 200){
          token.value = res.data;
          //Promise成功的返回值
          // console.log('token',token.value);
          return 'ok'
      }else{
        return Promise.reject(new Error(res.data))
      }
    };
    const userInfo = async () => {
      const res:userInfoData = await reqUserInfo()
      if(res.code === 200){
        userList.username = res.data.name
        userList.avatar = res.data.avatar
        return 'ok'
      }else{
        return Promise.reject(new Error(res.message))
      }
    }
    const userLogOut = async () => {
      const res = await reqLogout()
      console.log(res);
      token.value = '',
      userList.username = ''
      userList.avatar = ''
      localStorage.removeItem('token')
      // if(res.code === 200){
      //   return 'ok'
      // }else{
      //   return Promise.reject(new Error(res.message))
      // }
    }
    return { token, useLogin, menuRoutes,userInfo,userList,userLogOut};
  },
  {
    persist: true,
  }
);
export default useUserStore;
